using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class sParticles : MonoBehaviour
{
 	private static sParticles instance = null;

	private sParticles () {}

	public static sParticles Instance
	{
		get
		{
			return instance;
		}
	}
	
	void Awake()
	{
		instance = GetComponent<sParticles>();
		initialize();
	}
	
	public Dictionary<string, GameObject> m_moParticleEffectContainers;
	public Dictionary<string, GameObject> m_moParticleEffectOriginals;
	public List<GameObject> m_aoEffectInstances = new List<GameObject>();
	
	public void initialize()
	{		
		m_moParticleEffectContainers = new Dictionary<string, GameObject>();
		m_moParticleEffectOriginals = new Dictionary<string, GameObject>();
		
		// get all particle systems in a scene and store them in a map
		object[] aObj = GameObject.FindSceneObjectsOfType(typeof (GameObject));
		foreach (object o in aObj)
		{
		    GameObject g = (GameObject) o;
		    Debug.Log(g.name);
			
			if (g.GetComponent<ParticleEffectContainer>()) // if its not a container, add it to the normal particle effects
			{
				g.GetComponent<ParticleEffectContainer>().initialize();
				m_moParticleEffectContainers.Add(g.name, g);
				Debug.Log(g.name);
			}
			else if (g.GetComponent<ParticleSystem>())
			{
				m_moParticleEffectOriginals.Add(g.name, g);
			}
		}
	}
	
	public void SpawnEffect(string _sName, Vector3 _vPosition, Quaternion _vRotation)
	{
		if (m_moParticleEffectContainers.ContainsKey(_sName))
		{
			m_moParticleEffectContainers[_sName].GetComponent<ParticleEffectContainer>().spawn(_vPosition, _vRotation);
		}
		else
		{
		 	GameObject go = (GameObject)Instantiate(m_moParticleEffectOriginals[_sName], _vPosition, _vRotation);
			m_aoEffectInstances.Add(go);
		}
	}
	
	public void update()
	{
		for(int i=0; i<m_aoEffectInstances.Count; ++i)
		{
			bool bRemove = true;
			
			object[] aoParticleSystems = m_aoEffectInstances[i].GetComponents<ParticleSystem>();
			foreach(object o in aoParticleSystems)
			{
				ParticleSystem  ps = (ParticleSystem)o;
				if (ps.IsAlive())
				{
					bRemove = false;
					break;
				}
			}	
			if (bRemove)
			{
				Destroy(m_aoEffectInstances[i]);
				m_aoEffectInstances.RemoveAt(i);
				--i;
			}
		}
	}
}
